package it.asvp.asvp_portal.data.dao.impl;

import it.asvp.asvp_portal.data.dao.NewsDao;
import it.asvp.asvp_portal.data.entity.news.News;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class NewsDaoImpl implements NewsDao{

	private static final Log log = LogFactory.getLog(NewsDaoImpl.class);

	@Autowired
	private SessionFactory sessionFactory;

	public Long persist(News transientInstance) {
		log.debug("persisting News instance");
		Long id;
		try {
			id=(Long)sessionFactory.getCurrentSession().save(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
		return id;
	}

	public void delete(News persistentInstance) {
		log.debug("deleting News instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public News merge(News detachedInstance) {
		log.debug("merging News instance");
		try {
			News result = (News) sessionFactory.getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public News findById(java.lang.Long id) {
		log.debug("getting News instance with id: " + id);
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(News.class);
		cr.add(Restrictions.eq("id", id));
		News n = (News)cr.uniqueResult();
		return n;
	}
	
	@SuppressWarnings("unchecked")
	public List<News> findAll() {
		log.debug("getting all News instances");
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(News.class);
		List<News> list = (List<News>)cr.list();
		return list;
	}

}
